package com.neuedu.autosale.sys.controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.neuedu.autosale.entity.FileResult;
import com.neuedu.autosale.entity.Pager;
import com.neuedu.autosale.entity.Result;
import com.neuedu.autosale.sys.entity.Car;
import com.neuedu.autosale.sys.service.CarService;
import com.neuedu.autosale.util.FileuploadUtil;

@Controller
public class CarController {
	@Autowired
	private CarService carService;

	@RequestMapping("car/index")
	public String carInsex() {

		return "car/carlist";

	}

	@RequestMapping("car/findall")
	@ResponseBody
	public List<Car> findAll() {
		return carService.findAll();
	}

	@RequestMapping("car/list")
	@ResponseBody
	public Pager<Car> carlist(@RequestParam(value = "page", defaultValue = "1") Integer page,
			@RequestParam(value = "rows", defaultValue = "10") Integer rows) {
		Pager<Car> pager = new Pager<>(page, rows);
		List<Car> carlist = carService.findListByPager(pager);
		int total = carService.findTotalByPager(pager);
		pager.setRows(carlist);
		pager.setTotal(total);
		return pager;
	}

	@RequestMapping("car/add")
	@ResponseBody
	public Result doAdd(MultipartFile imageFile, Car car) {
		if (imageFile != null && !imageFile.isEmpty()) {
			FileResult fileResult = FileuploadUtil.uploadFile(imageFile);
			if (!fileResult.getSuccess()) {
				return new Result(false, fileResult.getMsg());
			}
			String serverFile = fileResult.getServerPath();
			car.setCarPhoto(serverFile);
		}
//		String serverFile = uploadFile(imageFile);
//		brand.setBrandPhoto(serverFile);
		Result result = carService.add(car);
		return result;
	}

	@RequestMapping("car/edit")
	@ResponseBody
	public Result doedit(MultipartFile imageFile, Car car) {
		if (imageFile != null && !imageFile.isEmpty()) {
			FileResult fileResult = FileuploadUtil.uploadFile(imageFile);
			if (!fileResult.getSuccess()) {
				return new Result(false, fileResult.getMsg());
			}
			String serverFile = fileResult.getServerPath();
			car.setCarPhoto(serverFile);
		}
//		String serverFile = uploadFile(imageFile);
//		brand.setBrandPhoto(serverFile);
		Result result = carService.edit(car);
		return result;
	}

	@RequestMapping("car/delete")
	@ResponseBody
	public Result doDelete(Integer carId) {
		List<Car> list = new ArrayList<Car>();
		list.add(new Car(carId));
		Result result = carService.deleteByIds(list);
		return result;
	}
}
